/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package be.fedict.barth.signer;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.bouncycastle.tsp.TSPException;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;

/**
 *
 * @author hanssens_bart
 */
public class TimeStamper {
    private static final String MIME_REQ = "application/timestamp-query";
    private static final String MIME_RESP = "application/timestamp-reply";
    
    private final TimeStampRequestGenerator tsrGen;
    
    public TimeStampResponse stamp(URL url, byte[] hash) throws IOException, TSPException {
        TimeStampRequest req = tsrGen.generate(Util.SHA256, hash);
        byte[] b = req.getEncoded();

        HttpURLConnection conn = Util.Post(url, MIME_REQ, MIME_RESP , b);
        TimeStampResponse resp = new TimeStampResponse(conn.getInputStream());
        resp.validate(req);
        conn.disconnect();
        
        return resp;
    }
    
    public TimeStamper() {
        tsrGen = new TimeStampRequestGenerator();
        tsrGen.setCertReq(true);
    }    
}